package study.linkedlist;

public class DoubleLinkedList {
    private Node2 head = new Node2(0, null);

    public Node2 getHead() {
        return head;
    }

    //添加节点
    public void add(Node2 newNode){
        Node2 temp = head;
        //遍历链表
        while (temp.next != null){
            //后移
            temp = temp.next;
        }
        //退出循环时，temp就是最后的节点
        temp.next = newNode;
        newNode.pre = temp;
    }

    //修改节点
    public void update(Node2 newNode){
        if (isEmpty()){
            System.out.println("链表为空");
            return;
        }

        Node2 temp = head;
        boolean flag = false;
        while (temp.next != null){
            //找到要修改的节点
            if (temp.id == newNode.id){
                flag = true;
                break;
            }

            //指针后移
            temp = temp.next;
        }
        if (flag){
            temp.data = newNode.data;
        }else {
            System.out.println("没有找到要修改的节点");
        }

    }

    //删除节点
    public void delete(int id){
        if(isEmpty()){
            System.out.println("链表为空");
            return;
        }
        Node2 temp = head.next;
        while (temp != null){
            if (id == temp.id){
                break;
            }
            temp = temp.next;
        }
        //temp就是找到的要删除的节点
        temp.pre.next = temp.next;
        temp.next.pre = temp.pre;

    }

    //打印链表
    public void list(){
        if (isEmpty()){
            System.out.println("链表为空");
            return;
        }
        Node2 temp = head.next;
        while (temp != null){
            System.out.println(temp);
            //指针后移
            temp = temp.next;
        }
    }

    public boolean isEmpty(){
        return head.next == null;
    }

    public void addByOrder(Node2 newNode){
        Node2 temp = head;
        boolean flag = false;
        while (temp.next != null){
            if (temp.next.id > newNode.id){
                break;
            }else if (temp.next.id == newNode.id){
                flag = true;
                break;
            }
            temp = temp.next;
        }

        if (flag){
            System.out.println(newNode.id + "节点已经添加过了，不能重复添加");
        }else {
            newNode.next = temp.next;
            temp.next = newNode;
            newNode.pre = temp;
        }
    }
}
